package com.mq.producer;

import com.alibaba.fastjson.JSON;
import com.mq.entity.MessagesBuild;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class MsgProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 消息发送
     * @param messagesBuild
     */
    private void sendMsg(MessagesBuild messagesBuild) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.setConfirmCallback((correlation, ack, cause) -> {
            System.out.println("correlationData--->" + correlation);
            System.out.println(ack);
            if (ack) {
                System.out.println("正常投递回复...");
                //后续执行其他业务...
            } else {
                System.out.println("投递异常....");
                //后续记录等操作...
            }
        });
        // 消息内容转json
        String msg = JSON.toJSONString(messagesBuild.getData());
        rabbitTemplate.convertAndSend(messagesBuild.getExchange(), messagesBuild.getRoutingKey(), msg, correlationData);
    }

    /**
     *
     * @param exchange
     * @param routingKey
     * @param data
     * @param <T>
     */
    public <T> void sendMsg(String exchange, String routingKey, T data) {
        log.info("消息投递");
        MessagesBuild messagesBuild = MessagesBuild.builder()
                                                   .exchange(exchange)
                                                   .routingKey(routingKey)
                                                   .data(data).build();
        this.sendMsg(messagesBuild);
    }
}
